package org.devknights.android.moneyeye;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.devknights.android.R;
import org.devknights.android.andlib.sms.SMSReader;
import org.devknights.android.andlib.sms.SMSUtil;
import org.devknights.android.moneyeye.core.activities.AccountDetails;
import org.devknights.android.moneyeye.core.adapters.ListViewAdapter;
import org.devknights.android.moneyeye.core.listners.SwipeListViewTouchListener;

import android.app.Activity;
import android.content.Intent;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class MoneyEye extends Activity 
{	 
	public final static String DATA = "org.devknights.android.moneyeye.DATA"; 
	
	public void onCreate(Bundle instance) {
		super.onCreate(instance);
		setTheme(android.R.style.Theme_Light);		
		
		setContentView(R.layout.activity_display_list_view);
		
        ListView lview = (ListView) findViewById(R.id.listview);
        List<Map<String,String>> list = populateList();
        ListViewAdapter adapter = new ListViewAdapter(this, list);         
        adapter.registerDataSetObserver(new DataSetObserver() {

			@Override
			public void onChanged()
			{				
				super.onChanged();				
			}
		});
        
        
        lview.setAdapter(adapter);       
        
        lview.setOnItemClickListener(new OnItemClickListener() 
        {
            public void onItemClick(AdapterView<?> parent, final View view,
                int position, long id) {
                        	Log.i("info", position+"");
                        	@SuppressWarnings("unchecked")
							Map<String,String> map = (Map<String,String>)parent.getAdapter().getItem(position);
                        	showDetails(view, map.get("Bank"));  	
                  };
            });
        
        SwipeListViewTouchListener touchListener = new SwipeListViewTouchListener(
        		lview, new SwipeListViewTouchListener.OnSwipeCallback() {
        			@Override
        			public void onSwipeLeft(ListView listView,
        					int[] reverseSortedPositions) 
        			{
        				Log.i("info", reverseSortedPositions[0]+"");
        				ListViewAdapter adapter = (ListViewAdapter)listView.getAdapter();
        				List<Map<String,String>> list = adapter.getList();
        				list.remove(reverseSortedPositions[0]);
        				adapter.notifyDataSetChanged();	
        				return;
        			}

        			@Override
        			public void onSwipeRight(ListView listView,
        					int[] reverseSortedPositions) 
        			{
        				Log.i("info", reverseSortedPositions[0]+"");
                    	@SuppressWarnings("unchecked")
						Map<String,String> map = (Map<String,String>)listView.getAdapter().getItem(reverseSortedPositions[0]);
                    	showDetails(listView, map.get("Bank"));  
                    	return;
        			}
        		}, true, // example : left action = dismiss
        		false); // example : right action without dismiss animation
        lview.setOnTouchListener(touchListener);
        // Setting this scroll listener is required to ensure that during
        // ListView scrolling,
        // we don't look for swipes.
        lview.setOnScrollListener(touchListener.makeScrollListener());
	}
	
	private List<Map<String,String>> populateList() {
		 
		List<Map<String,String>> list = new ArrayList<Map<String,String>>();
 
        Map<String,String> temp = new HashMap<String,String>();
            temp.put("Bank","HDFC BANK");
            temp.put("amount", "17000");
            temp.put("max", "20000");
            
        list.add(temp);
 
        Map<String,String> temp1 = new HashMap<String,String>();
        temp1.put("Bank","SBI BANK");
        temp1.put("amount", "10000");
        temp1.put("max", "50000");
        list.add(temp1);
        
        Map<String,String> temp2 = new HashMap<String,String>();
        temp2.put("Bank","ICICI BANK");
        temp2.put("amount", "3500");
        temp2.put("max", "75000");
        list.add(temp2);
 
        return list;        
    }
	
	private List<String> readSMS()
	{
		List<String> smsList = new ArrayList<String>();
		SMSReader sr = SMSUtil.readSMS(this, "inbox");

		while (sr.hasNext()) {
			smsList.add(sr.getString("address")+"=" + sr.getString("body"));
			sr.next();
		}
		
		return smsList;
	}
	
	private void writeToFile(List<String> list)
	{
		File sdCard = Environment.getExternalStorageDirectory();
		File dir = new File (sdCard.getAbsolutePath());
		dir.mkdirs();
		File file = new File(dir,"smsList.json");
		try{
		    FileOutputStream f1 = new FileOutputStream(file,false); //True = Append to file, false = Overwrite
		    PrintStream p = new PrintStream(f1);
		    
		    Iterator<String> iter = list.iterator();
		    String temp = "";
		    String [] tmpArr = null;
		    StringBuffer buffer = new StringBuffer("[");		    
		    
		    while(iter.hasNext())
		    {
		    	temp = iter.next();
		    	tmpArr = temp.split("=");
		    	buffer.append("{address:"+tmpArr[0]+",body:"+tmpArr[1]+"}");
		    	
		    	if(iter.hasNext())
		    		buffer.append(",");
		    }
		    
		    buffer.append("]");
		    
		    p.print(buffer.toString());
		    p.close();
		    f1.close();
		} catch (FileNotFoundException e) {
		} catch (IOException e) {
		} 
	}
	
	
	public void showDetails(View view, String map)
	{
		Intent intent = new Intent(this, AccountDetails.class);	
		intent.putExtra(DATA,map);
		startActivity(intent);
	}

}